<template>
	<div class='roleMaintain-container'>
		<vxe-grid ref='roleMaintainGridRef' v-bind='gridConfig'>
			<template v-slot:form>
				<n-flex align='center' justify='space-evenly'>
					<n-form-item label='角色名称' label-placement='left' :show-feedback='false'>
						<n-input v-model:value='gridConfig!.formConfig!.data.roleName' type='text'
								 placeholder='请输入角色名称' clearable/>
					</n-form-item>
					<n-form-item label='角色编码' label-placement='left' :show-feedback='false'>
						<n-input v-model:value='gridConfig!.formConfig!.data.roleCode' type='text'
								 placeholder='请输入角色编码' clearable/>
					</n-form-item>
					<n-form-item :show-label='false' :show-feedback='false'>
						<n-button round strong :bordered='false'
								  type='success' @click='initGrid'>
							搜索
						</n-button>
						<n-button round strong :bordered='false'
								  type='info' @click='reset'>
							重置
						</n-button>
					</n-form-item>
				</n-flex>
			</template>
			<template v-slot:toolbar_buttons>
				<n-button round strong @click='add'>
					<template v-slot:icon>
						<ClassIcon icon-class='fa fa-plus'/>
					</template>
					新增
				</n-button>
			</template>
			<template v-slot:toolbar_tools>
				<div class='vxe-custom--wrapper'>
					<n-button circle @click='initGrid'>
						<template v-slot:icon>
							<ClassIcon icon-class='fa fa-refresh'/>
						</template>
					</n-button>
					<!--<vxe-button
						circle icon='fa fa-download' title='导出Excel'
						@click='exportExcel'/>-->
				</div>
			</template>
			<template v-slot:operate='{ row }'>
				<n-button round strong @click='edit(row)'>
					<template v-slot:icon>
						<ClassIcon icon-class='fa fa-edit'/>
					</template>
				</n-button>
				<n-button round strong @click='remove(row)'>
					<template v-slot:icon>
						<ClassIcon icon-class='fa fa-remove'/>
					</template>
				</n-button>
			</template>
		</vxe-grid>
	</div>
	<AddModal ref='addModalRef' v-bind='addModalConfig' :optionList='optionList'/>
	<EditModal ref='editModalRef' v-bind='editModalConfig' :optionList='optionList'/>
</template>
<script setup lang='ts'>
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import axios from '@/config/axios/index.ts';
import { VxeGridInstance, VxeGridProps, VxeTableDefines, VxeTablePropTypes } from 'vxe-table';
import { VxeGrid, VxeUI } from '@/config/vxe/index.ts';
import { loadDict } from '@/config/dictionary/dictionary.ts';
import { showDictValueByKey1 } from '@/static/js/dict/format.ts';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import type { Dict } from '#/Dictionary.d.ts';
import type { Options } from '#/Options.d.ts';
import type { RoleProps } from '#/Role.d.ts';
// --------------------------------------------------------------------------------------------------------------
const ClassIcon = defineAsyncComponent(() => import('@/components/customComponents/icon/ClassIcon.vue'));
const AddModal = defineAsyncComponent(() => import('./addModal.vue'));
const EditModal = defineAsyncComponent(() => import('./editModal.vue'));
// --------------------------------------------------------------------------------------------------------------
const roleMaintainGridRef = ref<VxeGridInstance>();
const addModalRef = ref<InstanceType<typeof AddModal>>();
const editModalRef = ref<InstanceType<typeof EditModal>>();
// --------------------------------------------------------------------------------------------------------------
const dict = reactive<Dict>({});
// --------------------------------------------------------------------------------------------------------------
const addModalConfig = reactive({
	reLoad : () => initGrid()
});
const editModalConfig = reactive({
	reLoad : () => initGrid()
});
// --------------------------------------------------------------------------------------------------------------
const optionList = reactive<Options>({
	roleFeatures : {
		loading     : true,
		disabled    : true,
		placeholder : '',
		list        : [],
		map         : {}
	}
});
const gridConfig = reactive<VxeGridProps>({
	loading        : false,
	rowConfig      : {
		keyField : 'id'
	},
	height         : 'auto',
	align          : 'center',
	keyboardConfig : { isArrow : true },
	pagerConfig    : {
		currentPage : 1,
		pageSize    : 20,
		total       : 0
	},
	toolbarConfig  : {
		custom : {
			icon : 'fa fa-cog'
		}
	},
	formConfig     : {
		data : {
			roleName : null,
			roleCode : null
		}
	},
	columns        : [
		{
			field        : 'roleCode',
			title        : '角色编码',
			showOverflow : 'tooltip'
		},
		{
			field        : 'roleName',
			title        : '角色名称',
			showOverflow : 'tooltip'
		},
		{
			field        : 'roleFeatures',
			title        : '角色特征',
			showOverflow : 'tooltip',
			formatter    : (params: {
				cellValue: any,
				column: VxeTableDefines.ColumnInfo<VxeTablePropTypes.Row>,
				row: VxeTablePropTypes.Row
			}) => {
				return showDictValueByKey1('roleFeatures', dict, params.cellValue);
			}
		},
		{
			field        : 'sort',
			title        : '角色序号',
			showOverflow : 'tooltip'
		},
		{
			field        : 'status',
			title        : '是否启用',
			showOverflow : 'tooltip',
			cellRender   : {
				name   : 'n-switch',
				props  : {
					size           : 'large',
					checkedValue   : true,
					uncheckedValue : false,
					slots          : {
						checked   : '启用',
						unchecked : '禁用'
					}
				},
				events : {
					toggleEvent : async (row: any) => toggleStatus(row)
				}
			}
		},
		{
			title        : '操作',
			showOverflow : 'tooltip',
			slots        : {
				default : 'operate'
			}
		}
	],
	data           : [],
	// @ts-ignore
	onPageChange : (params: any) => changePage(params),
	// @ts-ignore
	onFormSubmit : () => initGrid()
});
onMounted(() => {
	// 加载字典
	loadDict(['roleFeatures']).then(async (dictResult: Dict) => {
		// 合并字典
		dict.roleFeatures = dictResult.roleFeatures;
		await initOptionList(dictResult);
		await initGrid();
	});
});
const initOptionList = async (dictResult: Dict): Promise<void> => {
	optionList.roleFeatures.list = dictResult.roleFeatures;
	optionList.roleFeatures.placeholder = '';
	optionList.roleFeatures.loading = false;
	optionList.roleFeatures.disabled = false;
};
const initGrid = async () => {
	gridConfig['loading'] = true;
	roleMaintainGridRef.value?.clearCurrentRow();
	roleMaintainGridRef.value?.clearCurrentColumn();
	axios<any, JsonResultProps<any>, any>({
		method : 'POST',
		url    : '/role/pagingList',
		data   : {
			...gridConfig.formConfig!.data,
			pageNum  : gridConfig.pagerConfig!.currentPage,
			pageSize : gridConfig.pagerConfig!.pageSize
		}
	}).then((jsonResult: JsonResultProps<any>) => {
		if (jsonResult.status) {
			gridConfig.pagerConfig!.total = jsonResult.data.total;
			gridConfig.data = jsonResult.data.records;
			gridConfig.loading = false;
		} else {
			VxeUI.modal.message({
				content : jsonResult.msg,
				status  : 'warning',
				id      : 'failedMessage'
			});
		}
	}).catch((error: unknown) => {
		console.error(error);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
	});
};
const changePage = async ({ currentPage, pageSize }: { currentPage: number, pageSize: number }) => {
	gridConfig['pagerConfig']!['currentPage'] = currentPage;
	gridConfig['pagerConfig']!['pageSize'] = pageSize;
	await initGrid();
};
const reset = async () => {
	gridConfig!.formConfig!.data.roleName = null;
	gridConfig!.formConfig!.data.roleCode = null;
	await initGrid();
};
const toggleStatus = async (rowData: RoleProps) => {
	gridConfig['loading'] = true;
	axios<any, JsonResultProps<any>, any>({
		method : 'PATCH',
		url    : `/role/status/${rowData.roleCode}`
	}).then(async (jsonResult: JsonResultProps<any>) => {
		if (jsonResult['status']) {
			await initGrid();
		} else {
			await VxeUI.modal.message({
				content : jsonResult.msg,
				status  : 'warning',
				id      : 'failedMessage'
			});
		}
	}).catch((error: unknown) => {
		gridConfig['loading'] = false;
		console.error(error);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
	});
};
const add = async () => {
	addModalRef.value?.showModal();
};
const edit = async (rowData: any) => {
	editModalRef.value?.showModal(rowData);
};
const remove = async (rowData: any) => {
	VxeUI.modal.confirm('确定删除该角色吗?').then((confirm: string) => {
		if ('confirm' === confirm) {
			axios<any, JsonResultProps<any>, any>({
				method : 'DELETE',
				url    : `/role/remove/${sessionStorage.getItem('loginTenantCode')}/${rowData.roleCode}`
			}).then(async (jsonResult: JsonResultProps<any>) => {
				if (jsonResult['status']) {
					await initGrid();
				} else {
					await VxeUI.modal.message({
						content : jsonResult.msg,
						status  : 'warning',
						id      : 'failedMessage'
					});
				}
			}).catch((error: unknown) => {
				gridConfig['loading'] = false;
				console.error(error);
				VxeUI.modal.message({
					content : '系统异常,请稍后再试',
					status  : 'error',
					id      : 'errorMessage'
				});
			});
		}
	});
};
</script>
<style scoped lang='scss'>
.roleMaintain-container{
	box-sizing :border-box;
	padding    :0;
	margin     :0;
	border     :0;
	height     :100%;
	width      :100%;
}
</style>